package com.example.Filter;

import com.example.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import com.alibaba.fastjson.JSONObject;
import com.example.msg.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
//@Component
public class LoginCheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("初始化！！！！！！！！！！！！！！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1、获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();
        log.info("请求的url:{}", url);

        //2、判断请求URL中是否包含login 如果包含说明是登录的操作 放行
        if (url.contains("login")) {
            log.info("登录操作，放行。。。");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3.获取请求头中的令牌
        String jwt = request.getHeader("token");

        //4、判断令牌是否存在 如果不存在 但会错误结果（未登录）
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，返回未登录的信息");
            Result result = Result.error("Not_LOGIN");
            //手动转换为json对象
            String notLogin = JSONObject.toJSONString(result);
            //响应给前端
            response.getWriter().write(notLogin);
            return;
        }
        // 5、解析token 如果解析失败 返回错误结果（ 未登录）
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result result = Result.error("Not_LOGIN");
            //手动转换为json对象
            String notLogin = JSONObject.toJSONString(result);
            //响应给前端
            response.getWriter().write(notLogin);
            return;
        }
        //6、放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("释放！！！！！！！！！！！！！！");
    }
}
